﻿using System;
using System.Collections.Generic;
using Mbs.ComponentModel.Container.Context;

namespace Mbs.ComponentModel.Container.Lifestyle
{
    [Serializable]
    public class PerThreadLifestyleManager : LifestyleManagerAdapter
    {

        [ThreadStatic]
        private static Dictionary<Guid, object> values = new Dictionary<Guid,object>();
        private readonly Guid key;

        /// <summary>
        /// Initializes a new instance of the <see cref="PerThreadLifetimeManager"/> class.
        /// </summary>
        public PerThreadLifestyleManager()
        {
            this.key = Guid.NewGuid();
        }

        public override object Get(ICreateContext ctx)
        {
            object result;
            EnsureValues();

            if (!values.TryGetValue(this.key, out result))
                result = values[key] = base.Get(ctx);
            return result;
        }

        public override bool Release(object instance)
        {
            EnsureValues();

            if (values.ContainsKey(key))
                values.Remove(key);

            return false;
        }

        public override bool Release()
        {
            return false;
        }

        
        private static void EnsureValues()
        {
            // no need for locking, values is TLS
            if (values == null)
            {
                values = new Dictionary<Guid, object>();
            }
        }
    }


    
}
